package com.zhiyou100.blog.utils;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author shkstart
 * @create 2021-03-14 9:50
 * 使用Druid数据库连接池技术
 */
public class JDBCUtils {
    public static void main(String[] args) throws SQLException {
        System.out.println(getConnection());
    }

    private static DataSource source;

    static {
        try {
            Properties properties = new Properties();
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(is);
            //根据提供的DruidDataSourceFactory创建对应的DataSource对象
            source = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取数据库连接
    public static Connection getConnection() throws SQLException {
        return source.getConnection();

    }

    /**
     * 关闭资源
     *
     * @param conn
     * @param ps
     */
    public static void closeResource(Connection conn, Statement ps) {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
    }

    /**
     * 关闭资源：使用dbutils.jar中提供的DbUtils工具类，实现资源的关闭
     *
     * @param conn
     * @param ps
     * @param rs
     */
    public static void closeResource(Connection conn, Statement ps, ResultSet rs) {
        try {
            DbUtils.close(conn);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            DbUtils.close(ps);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            DbUtils.close(rs);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
